package man

import (
	"dub/define/grpcmodel"
	"dub/secrec"
)

type AgentBaseFunController struct {
	AgentManBaseController
}

func (a *AgentBaseFunController) FindRegions() {
	a.Ctx.Request.ParseForm()
	result := make([]map[string]string, 0)
	first_rst := make(map[string]string)
	first_rst["RegionName"] = "请选择"
	first_rst["RegionCode"] = ""
	result = append(result, first_rst)
	for {
		level, _ := a.GetInt8("lve", 0)
		regionCode := a.GetString("regionCode", "")
		if level < 1 || (level > 1 && regionCode == "") {
			break
		}
		args := &grpcmodel.ModelSecRpcRegionReqFind{
			RegionCode: regionCode,
		}
		use_rpc := secrec.GetRpc(secrec.ConstServiceUseRpc)
		if use_rpc == nil {
			a.Log().Errorf("agent_base_controller.go FindRegions method not find use_rpc info GetRpc\n")
			break
		}
		sec_region := grpcmodel.NewISecRpcRegionClient(use_rpc.Conn())

		reply, err := sec_region.Find(use_rpc.Context(), args)
		if err != nil {
			a.Log().Errorf("agent_base_controller.go not find use_rpc info Call SecRegionRpc.FindLevRegions is %v\n", err)
			break
		}

		if reply.GetErr() != 0 {
			break
		}

		switch reply.GetDataType() {
		case 2:
			result = a.addRegionMap(result, reply.GetThiResions())
		case 1:
			result = a.addRegionMap(result, reply.GetTwoResions())
		case 0:
			result = a.addRegionMap(result, reply.GetFirResions())
		default:
			result = a.addRegionMap(result, reply.GetFirResions())
			result = a.addRegionMap(result, reply.GetTwoResions())
			result = a.addRegionMap(result, reply.GetThiResions())
		}
		break
	}
	a.Log().Infof("result info is %+v\n", result)
	a.Data["json"] = result
	a.ServeJSON()
}

func (a *AgentBaseFunController) addRegionMap(result []map[string]string, regions []*grpcmodel.ModelSecRpcRegion) []map[string]string {
	for _, region := range regions {
		first_rst := make(map[string]string)
		first_rst["RegionName"] = region.GetRegionName()
		first_rst["RegionCode"] = region.GetRegionCode()
		result = append(result, first_rst)
	}
	return result
}
